<template>
  <Dialog
    v-model:visible="dialog.visible"
    modal
    :header="dialogTitle"
    @show="openHandler"
    @hide="closeHandler"
  >
    <el-form
      ref="dataForm"
      :model="entity"
      :disabled="operation == 3"
      label-width="auto"
    >
      <el-row :gutter="20">
        <el-col :span="faceEnabled ? 12 : 24">
          <el-form-item
            prop="userAccount"
            label="用户账号"
            :rules="[
              { required: true, message: '请输入用户账号', trigger: 'blur' },
              {
                pattern: regular.enNum0to20,
                message: regular.enNum0to20Msg,
                trigger: 'blur',
              },
            ]"
          >
            <InputText
              v-model="entity.userAccount"
              placeholder="请输入用户账号"
              :disabled="entity.userBuiltIn"
            />
          </el-form-item>

          <el-form-item
            prop="userNickName"
            label="用户昵称"
            :rules="{
              pattern: regular.char0to20,
              message: regular.char0to20Msg,
              trigger: 'blur',
            }"
          >
            <InputText
              v-model="entity.userNickName"
              placeholder="请输入用户昵称"
            />
          </el-form-item>

          <el-form-item
            v-if="operation != 3"
            prop="userPassword"
            label="用户密码"
            :rules="[
              {
                required: operation == 1,
                message: '请输入用户密码',
                trigger: 'blur',
              },
              {
                pattern: regular.password,
                message: regular.passwordMsg,
                trigger: 'blur',
              },
            ]"
          >
            <InputGroup>
              <InputText
                v-model="entity.userPassword"
                placeholder="请输入用户密码"
              />
              <Button
                :icon="passwordLoading ? '' : 'pi pi-refresh'"
                :loading="passwordLoading"
                @click="getRandomPasswordHandler"
              />
            </InputGroup>
          </el-form-item>
        </el-col>

        <el-col v-if="faceEnabled" :span="12">
          <el-form-item prop="userFaceImage" label="人脸认证图像">
            <j-image-upload v-model="entity.userFaceImage">
              <template #button>
                <Button text @click="faceCameraDialog.visible = true"
                  >拍照</Button
                >
              </template>
            </j-image-upload>

            <j-face-camera-dialog
              :dialog="faceCameraDialog"
              @success="captureHandler"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            prop="userPhone"
            label="用户手机号"
            :rules="{
              pattern: regular.mobile,
              message: regular.mobileMsg,
              trigger: 'blur',
            }"
          >
            <InputText
              v-model="entity.userPhone"
              placeholder="请输入用户手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            prop="userEmail"
            label="用户邮箱"
            :rules="{
              type: 'email',
              message: '请输入正确的邮箱',
              trigger: 'blur',
            }"
          >
            <InputText
              v-model="entity.userEmail"
              placeholder="请输入用户邮箱"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            prop="roleIds"
            label="用户角色"
            :rules="{ required: true, message: '请选择角色', trigger: 'blur' }"
          >
            <MultiSelect
              v-model="entity.roleIds"
              :options="roles"
              dataKey="id"
              optionValue="id"
              optionLabel="roleName"
              placeholder="请选择角色"
              display="chip"
              :disabled="entity.userBuiltIn"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            prop="userDeptId"
            label="用户部门"
            :rules="{
              required: true,
              message: '请选择用户部门',
              trigger: 'blur',
            }"
          >
            <dept-tree-select
              v-model="entity.userDeptId"
              :disabled="entity.userBuiltIn"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="userEnable" label="用户是否启用">
            <ToggleSwitch
              v-model="entity.userEnable"
              :disabled="entity.userBuiltIn"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <cancel-button @click="dialog.visible = false" />
      <save-button
        v-if="operation != 3"
        :loading="loading"
        @click="saveHandler"
      />
    </template>
  </Dialog>
</template>
<script>
import JImageUpload from '@/components/JImageUpload'
import JFaceCameraDialog from '@/components/JFaceCamera/JFaceCameraDialog'

import { getDetail, save, update } from '@/api/upms/user'
import { fetchRoleList } from '@/api/personal'
import { randomCode } from '@/api/personal/common'
import { regular } from '@/utils/formRegular'
import MultiSelect from 'primevue/multiselect'

export default {
  name: 'UserEdit',
  props: {
    dialog: {
      type: Object,
      required: true,
    },
  },
  emits: ['success'],
  data() {
    return {
      loading: false,
      entity: {},
      titleMap: {
        1: '新建用户表',
        2: '编辑用户表',
        3: '查看用户表',
      },
      roles: [],
      passwordLoading: false,
      faceCameraDialog: {
        visible: false,
        value: null,
      },
    }
  },
  computed: {
    regular() {
      return regular
    },
    faceEnabled() {
      return window.config.faceEnabled
    },
    operation() {
      return this.dialog.operation
    },
    dialogTitle() {
      return this.titleMap[this.dialog.operation]
    },
  },
  components: { JImageUpload, JFaceCameraDialog },
  mounted() {
    fetchRoleList().then((res) => {
      this.roles = res.data.data
    })
  },
  methods: {
    openHandler() {
      if (this.dialog.entity && this.dialog.entity.id) {
        getDetail(this.dialog.entity.id).then((res) => {
          this.entity = res.data.data
          this.entity.userPassword = ''
          this.entity.roleIds = []
          for (let i in this.entity.roles) {
            this.entity.roleIds.push(this.entity.roles[i].id)
          }
        })
      } else {
        this.entity = {
          userEnable: true,
          roleIds: [],
          userDeptId: null,
        }
      }
    },
    closeHandler() {
      this.entity = {}
    },
    saveHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let edit = this.operation == 1 ? save : update
          edit(this.entity)
            .then(() => {
              this.dialog.visible = false
              this.$message.success('保存成功')
              this.$emit('success')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    getRandomPasswordHandler() {
      this.passwordLoading = true
      randomCode({
        upperCaseLetterLength: 2,
        lowerCaseLetterLength: 2,
        numLength: 4,
      }).then((res) => {
        this.passwordLoading = false
        this.entity.userPassword = res.data.data
      })
    },
    captureHandler() {
      this.entity.userFaceImage = this.faceCameraDialog.value
    },
  },
}
</script>
